from flask import render_template, current_app, session, request, jsonify

from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu
from info import constants


@index_blu.route("/news_list")
def news_list():
    """获取首页新闻数据"""
    # 1.get请求参数通过URL发过来
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")
    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="页码参数有误")
    # 3.查询数据
    filter = []
    if cid != 1:
        filter.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="数据查询错误")
    # 取当前页、总页数、当前页数
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li,
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


# 装饰器的作用是将路由映射到视图函数 index
@index_blu.route('/')
def index():
    # session["name"] = 'start'
    # logging.debug('测试DEBUG，这个logging时Python自带的，需要手动自己导包')
    # flask自带的打印日志，有横线区分打印的内容，并且会随项目设置的等级而打印日志
    # current_app.logger.error('测试调试')
    # redis_store.set('name', 'wang')
    # 如果用户已经登录，将当前登录用户数据传到模板中，供模板显示
    user_id = session.get("user_id", None)
    user = None
    # 取Session中的用户名，并创建对象
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    # 右侧新闻排行逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 查询分类数据，通过模板的形式渲染出来
    categories = Category.query.all()
    categor_li = []
    for category in categories:
        categor_li.append(category.to_dict())
    # 三元表达式，先判断if，为true则执行user.to_dict.false则直接返回None
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "category_li": categor_li,
    }

    return render_template('news/index.html',
                           data=data)


@index_blu.route('/favicon.ico')
def favicon():
    # 在打开网页的时候，浏览器会按照HTML文件需求的文件去请求根路径文件
    # send_static_file('file')时flask去查找指定静态文件的方法
    return current_app.send_static_file('news/favicon.ico')